package com.wuyan.locationdog.ui.msg


import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.amap.api.location.DPoint
import com.amap.api.maps.model.Circle
import com.amap.api.maps.model.CircleOptions
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Polygon
import com.amap.api.maps.model.PolygonOptions
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.district.DistrictSearch
import com.amap.api.services.district.DistrictSearchQuery
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.bean.Alarm
import com.arcsoft.commonbase.ext.customShowLong
import com.arcsoft.commonbase.ext.loadImageCircleCar
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.wuyan.locationdog.R
import com.wuyan.locationdog.databinding.MsgDetailMapActivityBinding
import com.wuyan.locationdog.help.DeviceHelp
import com.wuyan.locationdog.help.MsgHelp
import com.wuyan.locationdog.help.gpsSignalImg
import com.wuyan.locationdog.help.gpsSignalText
import com.wuyan.locationdog.ui.device.TrackDetailActivity
import com.wuyan.locationdog.util.maputil.MapLifecycle
import com.wuyan.locationdog.util.maputil.MapHelp
import com.wuyan.locationdog.view.TipPopup
import com.wuyan.locationdog.viewmodel.DeviceViewModel
import com.wuyan.locationdog.viewmodel.MsgViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MsgDetailMapActivity : BaseBindingActivity<MsgDetailMapActivityBinding>() {
    private lateinit var mAlarm: Alarm
    private val mViewModel: MsgViewModel by viewModels()
    private val mDeviceViewModel: DeviceViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycle.addObserver(MapLifecycle(binding.mapView, savedInstanceState))

    }


    override fun initData() {
        BarUtils.transparentStatusBar(this)
        binding.apply {
            btnBack.setOnClickListener {
                finish()
            }
        }

    }

    override fun loadNetData() {
        super.loadNetData()
        val map = HashMap<String, Any>()
        map["userNoticeId"] = MsgHelp.instantMsgBeanContent.userNoticeId
        mViewModel.msgDetail(map)

    }

    override fun observe() {
        super.observe()

        mViewModel.msgDetail.observe(this) {
            it.content.alarm.let {

                mAlarm = it
                binding.apply {
                    deviceName.text = it.deviceName
                    deviceId.text = "设备ID：" + it.imei
                    alarmTypeDesc.text = it.alarmTypeDesc
                    alarmStartTime.text = "更新时间：" + it.alarmStartTime
                    speed.text = it.speed.toString() + "公里/小时" + " | " + "行驶方向：" + it.directDesc
                    gpsSignal.text = gpsSignalText(it.gpsSignal.toInt())
                    gpsSignalImageView.setImageResource(gpsSignalImg(it.gpsSignal.toInt()))

                    power.text = it.power.toString() + "%"

                    deviceAvatarUrl.loadImageCircleCar(it.deviceAvatarUrl)
                    geocodeSearch(
                        LatLonPoint(
                            it.lat,
                            it.lng
                        )
                    )

                    MapHelp.setMapBounds(mapView, mutableListOf(LatLng(it.lat, it.lng)))
                }


                val map = HashMap<String, Any>()
                map["imei"] = it.imei
                mDeviceViewModel.mapDeviceLocation(map)
            }
        }

        mDeviceViewModel.deviceDetailBean.observe(this) {
            it.content.deviceDetailVO.deviceAvatarUrl = mAlarm.deviceAvatarUrl
            it.content.gaoDeLat = mAlarm.lat
            it.content.gaoDeLng = mAlarm.lng


            DeviceHelp.selectDeviceBeanContent = it.content
            binding.apply {
//                mapView.map.clear(true)
                MapHelp.getMarkerUi(layoutInflater, it.content) {
                    mapView.map.addMarker(it).`object` = DeviceHelp.selectDeviceBeanContent
                }


                btnFence.setOnClickListener {
                    if (isFenceChecked) {
                        fenceStatus.text = "关闭围栏"
                        val map = HashMap<String, Any>()
                        map["deviceId"] = DeviceHelp.selectDeviceBeanContent.deviceId
                        mDeviceViewModel.areaList(map)
                    } else {
                        fenceStatus.text = "查看围栏"

                        mCircleList.forEach {
                            it.remove()
                        }
                        mPolygonList.forEach {
                            it.remove()
                        }
                    }

                    isFenceChecked = !isFenceChecked

                }
                btnDeviceGuiJi.setOnClickListener {
                   val time =  mAlarm.alarmStartTime.subSequence(0, "yyyy-MM-dd".length).toString()
                    DeviceHelp.startTime = "$time 00:00:00"
                    DeviceHelp.endTime = "$time 23:59:59"

                    val map = HashMap<String, Any>()
                    map["imei"] = DeviceHelp.selectDeviceBeanContent.imei
                    map["startTime"] = DeviceHelp.startTime
                    map["endTime"] = DeviceHelp.endTime
                    mDeviceViewModel.deviceLocationRecord(map) {
                        TipPopup(
                            mActivity,
                            R.mipmap.pop_track,
                            "未查询到轨迹信息",
                            "抱歉，当前时间范围内无轨迹信息。可能设备尚未启用或设备已经离线 ！",
                            "知道了"
                        ).showPopupWindow()

                    }
                }
            }
        }

        mDeviceViewModel.fenceBean.observe(this) {
            mCircleList.clear()
            mPolygonList.clear()
            allLatLngs.clear()
            it.content.forEach {
                if (it.type == 4) {
                    if (it.district.isNullOrEmpty()) {
                        return@observe
                    }
                    if (it.district.contains(",")) {
                        val split = it.district.split(",")
                        provinceCitySearch(split[0], split[1])
                    } else {
                        provinceCitySearch(it.district, "")
                    }
                } else {
                    val centerPoint = DPoint()
                    centerPoint.latitude = it.coordinate.split(",")[0].toDouble()
                    centerPoint.longitude = it.coordinate.split(",")[1].toDouble()
                    drawCircle(centerPoint, it.radis.toFloat() * 1000.toDouble())
                }
            }

        }


        mDeviceViewModel.trackBean.observe(this) {
            DeviceHelp.instantTrackBeanContent = it.content
            ActivityUtils.startActivity(TrackDetailActivity::class.java)

        }

    }

    /**
     * 逆地理编码
     */
    fun geocodeSearch(latLonPoint: LatLonPoint) {
        val geocoderSearch = GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
            override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult, p1: Int) {
//                1）可以在回调中解析result，获取地址、adcode等等信息。
//
//                2）返回结果成功或者失败的响应码。1000为成功，其他为失败（详细信息参见网站开发指南-实用工具-错误码对照表）
                val regeocodeAddress = regeocodeResult.regeocodeAddress
                binding.apply {
                    SpanUtils.with(desc)
                        .append(regeocodeAddress.formatAddress)
                        .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_3))
                        .appendImage(R.mipmap.copy)
                        .create()
                    desc.setOnClickListener {
                        ClipboardUtils.copyText(regeocodeAddress.formatAddress)
                        customShowLong("复制成功")
                    }

                }
            }

            override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {

            }
        });

        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        val query = RegeocodeQuery(latLonPoint, 200f, GeocodeSearch.AMAP)
        geocoderSearch.getFromLocationAsyn(query)
    }
    private var isFenceChecked: Boolean = true

    private val mCircleList = mutableListOf<Circle>()
    private val mPolygonList = mutableListOf<Polygon>()
    private val allLatLngs: MutableList<LatLng> = ArrayList()

    //绘制圆形
    private fun drawCircle(centerPoint: DPoint, radius: Double) {
//        circle?.remove()
        val option = CircleOptions()
        option.fillColor(Color.parseColor("#1A1259FF"))
        option.strokeColor(Color.parseColor("#6E4DF3"))
        option.strokeWidth(SizeUtils.dp2px(2F).toFloat())
        option.radius(radius)

        val latLng = LatLng(centerPoint.latitude, centerPoint.longitude)
        option.center(latLng)
        val circle = binding.mapView.map.addCircle(option)
        mCircleList.add(circle!!)

//        MapHelp.setMapBounds(binding.mapView, mutableListOf(latLng))

    }

    fun provinceCitySearch(provinceName: String, cityName: String) {
        val search = DistrictSearch(mActivity)
        val query = DistrictSearchQuery()

        if (cityName.isNotEmpty()) {
            query.keywordsLevel = DistrictSearchQuery.KEYWORDS_CITY
            query.keywords = cityName //传入关键字

        } else {
            query.keywordsLevel = DistrictSearchQuery.KEYWORDS_PROVINCE
            query.keywords = provinceName //传入关键字
        }
        query.isShowBoundary = true //是否返回边界值

        search.query = query
        search.setOnDistrictSearchListener {
            drawProvinceCity(it.district.first().districtBoundary())
        }
        search.searchDistrictAnsy() //开始搜索

    }


    fun drawProvinceCity(it: Array<String>) {
        lifecycleScope.launch(Dispatchers.IO) {
            it.forEach {
                val latLngs: MutableList<LatLng> = ArrayList()

                if (!it.contains("|")) {
                    val split = it.split(";")
                    split.forEach {
                        val strings = it.split(",")
                        latLngs.add(LatLng(strings.last().toDouble(), strings.first().toDouble()))
                    }
                } else {
                    Log.e("岛屿", "drawProvinceCity: " + it)
                }
                allLatLngs.addAll(latLngs)
                val polygonOptions = PolygonOptions()
                    .addAll(latLngs) // latLngs是一个包含多边形所有顶点的List<LatLng>
                    .fillColor(Color.parseColor("#1A1259FF"))
                    .strokeColor(Color.parseColor("#6E4DF3"))
                    .strokeWidth(2f) // 边界线宽度

                withContext(Dispatchers.Main) {
                    // 创建多边形填充区域
                    val polygon = binding.mapView.map.addPolygon(polygonOptions)
                    mPolygonList.add(polygon!!)
                }
            }
            MapHelp.setMapBounds(binding.mapView, allLatLngs)

        }


    }

}